/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controlers.Admin;

import Pojos.ChiTietSanPham;
import Pojos.DanhMucSanPham;
import Pojos.HangSanXuat;
import Pojos.NhaPhanPhoi;
import Pojos.NhomSanPham;
import Pojos.SanPham;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.dom4j.DocumentException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.google.gson.Gson;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;
import javax.servlet.http.HttpSession;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author ToanNhan
 */
public class ThemSanPham extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        if (request.getParameter("command") == null) {
            response.sendRedirect("/WebsiteBanHang/Admin/ThemSanPham.jsp");
        }
        String command = request.getParameter("command");        
        if (command != null) {

            command = command.toLowerCase();
            if (command.compareTo("laydanhsachnhomsanpham") == 0) {
                layDanhSachNhomSanPham(request, response);
            }

            if (command.compareTo("themnhomsanpham") == 0) {
                themNhomSanPham(request, response);
            }

            if (command.compareTo("laymauchitiettheomanhomsanpham") == 0) {
                layMauChiTietTheoMaNhomSanPham(request, response);
            }

            if (command.compareTo("themhangsanxuat") == 0) {
                themHangSanXuat(request, response);
            }

            if (command.compareTo("laydanhsachhangsanxuat") == 0) {
                layDanhSachHangSanXuat(request, response);
            }

            if (command.compareTo("themnhaphanphoi") == 0) {
                themNhaPhanPhoi(request, response);
            }

            if (command.compareTo("laydanhsachnhaphanphoi") == 0) {
                layDanhSachNhaPhanPhoi(request, response);
            }

            if (command.compareTo("luuthongtinsanpham") == 0) {
                themSanPham(request, response);
            }

            if (command.compareTo("uploadhinhanh") == 0) {
                uploadHinhAnh(request, response);
            }

            if (command.compareTo("xoahinhanh") == 0) {
                HttpSession session = request.getSession();
                session.removeAttribute("hinhSanPham");
            }

            if (command.compareTo("laydanhmucsanpham") == 0) {
                layDanhMucSanPham(request, response);
            }

            if (command.compareTo("themdanhmucsanpham") == 0) {
                themDanhMucSanPham(request, response);
            }
        }


    }

    protected void themNhomSanPham(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter out = response.getWriter();
        String tenNhomSanPham = request.getParameter("tennhomsanpham");
        System.out.println(tenNhomSanPham);
        InputStream ip = request.getInputStream();
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        byte buf[] = new byte[512];
        int count = 0;
        while ((count = ip.read(buf, 0, 512)) > 0) {
            buffer.write(buf, 0, count);
        }
        String mauChiTietNhomSanPham = new String(buffer.toByteArray(), "UTF-8");
        NhomSanPham nhomSanPham = new NhomSanPham();
        nhomSanPham.setMaNhomSanPham("N001");
        nhomSanPham.setTenNhomSanPham(tenNhomSanPham);
        nhomSanPham.setMauNhomChiTiet(mauChiTietNhomSanPham);
        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        session.beginTransaction();
        Query query = session.createQuery("from NhomSanPham");
        int soLuong = query.list().size();
        nhomSanPham.setMaNhomSanPham("N" + soLuong);
        session.save(nhomSanPham);
        session.getTransaction().commit();
        session.close();

    }

    protected void layDanhSachNhomSanPham(HttpServletRequest request, HttpServletResponse respone) throws IOException {
        respone.setContentType("application/json");
        PrintWriter out = respone.getWriter();

        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        Query query = session.createQuery("Select maNhomSanPham, tenNhomSanPham from NhomSanPham");
        List<NhomSanPham> dsNhomSanPham = query.list();        
        String json = new Gson().toJson(dsNhomSanPham);
        out.print(json);
        out.flush();
        out.close();
        session.close();
    }

    protected void layMauChiTietTheoMaNhomSanPham(HttpServletRequest request, HttpServletResponse respone) throws IOException {
        PrintWriter out = respone.getWriter();
        String maNhomSanPham = request.getParameter("MaNhomSanPham");
        if (maNhomSanPham != null) {
            SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
            Session session = factory.openSession();
            Query query = session.createQuery("from NhomSanPham where maNhomSanPham = ?");
            query.setString(0, maNhomSanPham);
            NhomSanPham nhomSanPham = (NhomSanPham) query.uniqueResult();
            if (nhomSanPham != null) {
                String mauChiTiet = nhomSanPham.getMauNhomChiTiet();
                try {
                    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(mauChiTiet)));
                    Node root = document.getFirstChild();
                    NodeList childRoot = root.getChildNodes();
                    String str = "<table width=\"90%\">";
                    int m = 1;
                    for (int i = 0; i < childRoot.getLength(); i++) {
                        Node child = childRoot.item(i);
                        str += "<tr bgcolor=\"bisque\"><td colspan=\"2\" align=\"center\">";
                        str += child.getAttributes().item(0).getNodeValue();
                        str += "</td></tr>";
                        NodeList elementChild = child.getChildNodes();
                        for (int j = 0; j < elementChild.getLength(); j++) {
                            if (m % 2 == 0) {
                                str += "<tr bgcolor=\"bisque\">";
                            } else {
                                str += "<tr>";
                            }

                            NamedNodeMap map = elementChild.item(j).getAttributes();
                            str += "<td>" + map.item(0).getNodeValue() + "</td>";
                            str += "<td><input type=\"text\" name=" + m + "></input></td>";
                            str += "</tr>";
                            m++;
                        }
                    }
                    if (m % 2 == 0) {
                        str += "<tr bgcolor=\"bisque\">";
                    } else {
                        str += "<tr>";
                    }

                    str += "<td colspan=\"2\"><input name=\"btn\" type=\"submit\" value=\"Lưu\"/></td>";
                    str += "</table>";
                    str += "<input type=\"hidden\" name=\"command\" value=\"LuuThongTinSanPham\"/>";
                    out.write(str);

                } catch (ParserConfigurationException ex) {
                    Logger.getLogger(ThemSanPham.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SAXException ex) {
                }
            }

            session.close();
        } else {
            out.println("<td colspan=\"2\">Có lỗi xảy ra</td>");
        }
        out.flush();
        out.close();

    }

    protected void themHangSanXuat(HttpServletRequest request, HttpServletResponse respone) throws IOException {
        respone.setContentType("application/json");
        PrintWriter out = respone.getWriter();
        String maHangSanXuat = request.getParameter("MaHangSanXuat");
        String tenHangSanXuat = request.getParameter("TenHangSanXuat");
        String err = "";
        if (maHangSanXuat == null || maHangSanXuat.length() == 0) {
            err = "Bạn chưa nhập mã hãng sản xuất\n";
        }
        if (tenHangSanXuat == null || tenHangSanXuat.length() == 0) {
            err += "Bạn chưa nhập tên hãng sản xuất";
        }
        if (err == "") {
            try {
                HangSanXuat hangSanXuat = new HangSanXuat(maHangSanXuat, tenHangSanXuat);
                SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
                Session session = factory.openSession();
                session.beginTransaction();
                session.save(hangSanXuat);
                session.getTransaction().commit();
                System.out.println("Đã lưu thành công");
                Query query = session.createQuery("Select maHangSanXuat, tenHangSanXuat from HangSanXuat");
                List<HangSanXuat> dsHangSanXuat = query.list();                
                String json = new Gson().toJson(dsHangSanXuat);
                out.print(json);
                out.flush();
                out.close();
                session.close();
            } catch (Exception ex) {
                out.println(ex.getMessage());
                out.flush();
                out.close();
            }
        } else {
            out.println(err);
            out.flush();
            out.close();
        }
    }

    protected void layDanhSachHangSanXuat(HttpServletRequest request, HttpServletResponse respone) throws IOException {
        respone.setContentType("application/json");
        PrintWriter out = respone.getWriter();
        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        session.beginTransaction();
        Query query = session.createQuery("Select maHangSanXuat, tenHangSanXuat from HangSanXuat");
        List<HangSanXuat> dsHangSanXuat = query.list();        
        session.close();
        String json = new Gson().toJson(dsHangSanXuat);
        out.print(json);
        out.flush();
        out.close();
    }

    protected void themNhaPhanPhoi(HttpServletRequest request, HttpServletResponse respone) throws IOException {
        respone.setContentType("application/json");
        PrintWriter out = respone.getWriter();
        String maNhaPhanPhoi = request.getParameter("MaNhaPhanPhoi");
        String tenNhaPhanPhoi = request.getParameter("TenNhaPhanPhoi");
        String diaChi = request.getParameter("DiaChi");
        String err = "";
        if (maNhaPhanPhoi == null || maNhaPhanPhoi.length() == 0) {
            err = "Bạn chưa nhập mã nha phan phoi\n";
        }
        if (tenNhaPhanPhoi == null || tenNhaPhanPhoi.length() == 0) {
            err += "Bạn chưa nhập tên nhà phân phối";
        }
        if (diaChi == null || diaChi.length() == 0) {
            err += "Bạn chưa nhập địa chỉ của nhà phân phối";
        }
        if (err == "") {
            try {
                NhaPhanPhoi nhaPhanPhoi = new NhaPhanPhoi(maNhaPhanPhoi, tenNhaPhanPhoi, diaChi);
                SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
                Session session = factory.openSession();
                session.beginTransaction();
                session.save(nhaPhanPhoi);
                session.getTransaction().commit();
                System.out.println("Đã lưu thành công");
                Query query = session.createQuery("Select maNhaPhanPhoi, tenNhaPhanPhoi from NhaPhanPhoi");
                List<HangSanXuat> dsNhaPhanPhoi = query.list();                
                String json = new Gson().toJson(dsNhaPhanPhoi);
                out.print(json);
                out.flush();
                out.close();
                session.close();
            } catch (Exception ex) {
                out.println(ex.getMessage());
                out.flush();
                out.close();
            }
        } else {
            out.println(err);
            out.flush();
            out.close();
        }
    }

    protected void layDanhSachNhaPhanPhoi(HttpServletRequest request, HttpServletResponse respone) throws IOException {
        respone.setContentType("application/json");
        PrintWriter out = respone.getWriter();

        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        Query query = session.createQuery("Select maNhaPhanPhoi, tenNhaPhanPhoi from NhaPhanPhoi");
        List<NhaPhanPhoi> dsNhaPhanPhoi = query.list();        
        String json = new Gson().toJson(dsNhaPhanPhoi);
        out.print(json);
        out.flush();
        out.close();
        session.close();
    }

    protected void themSanPham(HttpServletRequest request, HttpServletResponse respone) throws IOException {
        String tenSanPham = request.getParameter("tenSanPham");
        HttpSession session = request.getSession();
        String hinhSanPham = (String) session.getAttribute("hinhSanPham");
        String giaBan = request.getParameter("giaBan");
        String xuatXu = request.getParameter("xuatXu");
        String thongTinBaoHanh = request.getParameter("thongTinBaoHanh");
        String maHangSanXuat = request.getParameter("hangSanXuat");
        String maNhaPhanPhoi = request.getParameter("nhaPhanPhoi");
        String maNhomSanPham = request.getParameter("nhomSanPham");
        String maDanhMuc = request.getParameter("danhMucSanPham");
        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session sessionHibernate = factory.openSession();
        Query query = sessionHibernate.createQuery("from NhomSanPham where maNhomSanPham = ?");
        query.setString(0, maNhomSanPham);
        NhomSanPham nhomSanPham = (NhomSanPham) query.uniqueResult();
        query = sessionHibernate.createQuery("from SanPham");
        int numOfSanPham = query.list().size();
        sessionHibernate.close();

        String mauChiTiet = nhomSanPham.getMauNhomChiTiet();
        String chiTiet = "";
        try {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(mauChiTiet)));
            Node root = document.getFirstChild();
            NodeList childRoot = root.getChildNodes();
            int count = 1;
            for (int i = 0; i < childRoot.getLength(); i++) {
                NodeList elementChild = childRoot.item(i).getChildNodes();
                for (int j = 0; j < elementChild.getLength(); j++) {
                    NamedNodeMap map = elementChild.item(j).getAttributes();
                    map.item(1).setNodeValue(request.getParameter(String.valueOf(count)));
                    count++;
                }
            }
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            DOMSource source = new DOMSource(document);

            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            DataOutputStream dos = new DataOutputStream(buffer);
            StreamResult result = new StreamResult(dos);
            transformer.transform(source, result);

            chiTiet = buffer.toString("UTF8");

        } catch (TransformerException ex) {
            Logger.getLogger(ThemSanPham.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(ThemSanPham.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
        }
        if (hinhSanPham != null){
            File file = new File(hinhSanPham);
        String name = file.getName().substring(0, file.getName().length() - 4);
        hinhSanPham = hinhSanPham.replaceAll(name, "SP" + numOfSanPham + 1);
        file.renameTo(new File(hinhSanPham));
        hinhSanPham = "/images/sanpham/" + ("SP" + numOfSanPham + 1) + file.getName().substring(file.getName().length() - 4);
        } else{
            hinhSanPham = "";
        }
        
        SanPham sanPham = new SanPham();
        sanPham.setBaoHanh(thongTinBaoHanh);
        sanPham.setDanhMucSanPham(new DanhMucSanPham(maDanhMuc));
        sanPham.setGiaBan(Long.valueOf(giaBan));
        sanPham.setHangSanXuat(new HangSanXuat(maHangSanXuat));
        sanPham.setHinhSanPham(hinhSanPham);
        sanPham.setMaSanPham("SP" + numOfSanPham + 1);
        sanPham.setNhaPhanPhoi(new NhaPhanPhoi(maNhaPhanPhoi));
        sanPham.setNhomSanPham(nhomSanPham);
        sanPham.setSoLuotMua(0);
        sanPham.setSoLuotXem(0);
        sanPham.setTenSanPham(tenSanPham);
        sanPham.setXuatXu(xuatXu);
        ChiTietSanPham chiTietSanPham = new ChiTietSanPham("SP" + numOfSanPham + 1, chiTiet);
        sessionHibernate = factory.openSession();
        sessionHibernate.beginTransaction();
        sessionHibernate.save(sanPham);
        sessionHibernate.save(chiTietSanPham);
        sessionHibernate.getTransaction().commit();
        sessionHibernate.close();
        respone.sendRedirect("/WebsiteBanHang/Admin/ThemSanPhamThanhCong.jsp");
    }

    protected void uploadHinhAnh(HttpServletRequest request, HttpServletResponse respone) {
        String fileName = request.getParameter("tenTapTin");
        String fullName = request.getRealPath("images/sanpham") + "\\" + fileName;
        File file = new File(fullName);
        try {
            FileOutputStream fos = new FileOutputStream(file, false);
            InputStream is = request.getInputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while ((count = is.read(buffer, 0, 1024)) > 0) {
                fos.write(buffer, 0, count);
            }
            fos.close();
            is.close();
            HttpSession session = request.getSession();
            session.setAttribute("hinhSanPham", fullName);
            respone.setHeader("status", "complete");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(ThemSanPham.class.getName()).log(Level.SEVERE, null, ex);
            respone.setHeader("status", "failed");
        } catch (IOException ex) {
            Logger.getLogger(ThemSanPham.class.getName()).log(Level.SEVERE, null, ex);
            respone.setHeader("status", "failed");
        }

    }

    protected void layDanhMucSanPham(HttpServletRequest request, HttpServletResponse respone) throws IOException {
        respone.setContentType("application/json");
        PrintWriter out = respone.getWriter();

        SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
        Session session = factory.openSession();
        Query query = session.createQuery("Select maDanhMuc, tenDanhMuc from DanhMucSanPham");
        List<DanhMucSanPham> dsDanhMucSanPham = query.list();        
        String json = new Gson().toJson(dsDanhMucSanPham);
        out.print(json);
        out.flush();
        out.close();
        session.close();
    }

    protected void themDanhMucSanPham(HttpServletRequest request, HttpServletResponse respone) throws IOException {
        String tenDanhMucSanPham = request.getParameter("tenDanhMucSanPham");
        if (tenDanhMucSanPham != null) {
            SessionFactory factory = new Configuration().configure("Pojos/hibernate.cfg.xml").buildSessionFactory();
            Session session = factory.openSession();
            Query query = session.createQuery("from DanhMucSanPham");
            List<DanhMucSanPham> lst = query.list();
            String maDanhMuc = "DM" + lst.size();
            DanhMucSanPham dm = new DanhMucSanPham(maDanhMuc, tenDanhMucSanPham);
            session.beginTransaction();
            session.save(dm);
            session.getTransaction().commit();

            respone.setContentType("application/json");
            PrintWriter out = respone.getWriter();
            query = session.createQuery("Select maDanhMuc, tenDanhMuc from DanhMucSanPham");
            lst = query.list();            
            String json = new Gson().toJson(lst);
            out.print(json);
            out.flush();
            out.close();
            session.close();

        }
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
